#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>

#define NUM 128
#define SIZE 32

char _command[NUM];
char* _tok_command[SIZE];
int main(){
  while(1){
    memset(_command,'\0',NUM);
     //gethostname(_command,128);
    //printf("%s\n",_command);
    //sleep(1);
    
    //1.打印与shell格式相对应的前半段
    char* curname[128];
    gethostname(curname,128);
    printf("[zgy@%s]",curname);
    
    //2.输入命令行参数
    if(fgets(_command,NUM,stdin)){
      _command[strlen(_command)-1] = '\0';
      //printf("%s\n",_command);
      
      //3.解析命令行参数
      int index = 0;
      _tok_command[index] = strtok(_command," ");
      while(1){
        ++index;
        _tok_command[index] = strtok(NULL," ");
        if(_tok_command[index] == NULL){
          break;
        }
      }

      if(strcmp(_tok_command[0],"cd") == 0 && chdir(_tok_command[1]) == 0){
        continue; //需要父进程执行的命令
      }

      //4.用execvp进行程序替换
      if(fork()==0){
        execvp(_tok_command[0],_tok_command);
        exit(1);
      }

      //5.父进程等待子进程退出
      int status = 0;
      pid_t ret = waitpid(-1,&status,0);
      if(ret > 0 && WIFEXITED(status)){
        printf("Exit Code:%d\n",WEXITSTATUS(status));
      }

    }
  }
  return 0;
}
